<!--
 * @Author: liu
 * @Date: 2024-04-04 18:33:11
 * @LastEditors: liu
 * @LastEditTime: 2024-04-11 00:11:58
 * @FilePath: \yyx_admin\src\views\courses\components\UploadVod.vue
 * @Description: 
 * 天道酬勤
-->
<template>
  <div class="container">
    <div class="upload">
      <div>
        <input type="file" id="fileUpload" @change="fileChange($event)" />
        <label class="status"
          >上传状态: <span>{{ statusText }}</span></label
        >
      </div>
      <div class="upload-type">
        上传方式一, 使用 UploadAuth 上传:
        <button @click="authUpload" :disabled="vod.uploadDisabled">
          开始上传
        </button>
        <!-- <button @click="pauseUpload" :disabled="pauseDisabled">暂停</button> -->
        <!-- <button :disabled="resumeDisabled" @click="resumeUpload">
          恢复上传
        </button> -->
        <span class="progress"
          >上传进度: <i id="auth-progress">{{ vod.authProgress }}</i> %</span
        >
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import axios from 'axios'

let statusText = ref('')
const vod: any = reactive({
  timeout: '',
  partSize: 0,
  parallel: '',
  retryCount: '',
  retryDuration: '',
  file: null,
  uploader: null,
  authProgress: 0,
  statusText: '',
  region: 'cn-shanghai',
  userId: '1303984639806000',
  uploadDisabled: true,
  resumeDisabled: true,
  pauseDisabled: true
})

const createUploader = () => {
  let uploader = new AliyunUpload.Vod({
    timeout: vod.timeout || 60000,
    partSize: Math.round(vod.partSize || 1048576),
    parallel: vod.parallel || 5,
    retryCount: vod.retryCount || 3,
    retryDuration: vod.retryDuration || 2,
    region: vod.region,
    userId: vod.userId,
    localCheckpoint: true, //此参数是禁用服务端缓存，不影响断点续传
    // 添加文件成功
    addFileSuccess: function (uploadInfo: any) {
      console.log(uploadInfo.videoId, 'uploadInfo.videoIdadd')
      vod.uploadDisabled = false
      vod.resumeDisabled = false
      vod.statusText = '添加文件成功, 等待上传...'
      console.log('addFileSuccess: ' + uploadInfo.file.name)
    },
    //开始上传
    onUploadstarted: function (uploadInfo: any) {
      console.log(uploadInfo, 'uploadInfo....')
      // console.log(uploadInfo.file, 'uploadInfo')

      //return
      // 如果是 UploadAuth 上传方式, 需要调用 uploader.setUploadAuthAndAddress 方法
      // 如果是 UploadAuth 上传方式, 需要根据 uploadInfo.videoId是否有值，调用点播的不同接口获取uploadauth和uploadAddress
      // 如果 uploadInfo.videoId 有值，调用刷新视频上传凭证接口，否则调用创建视频上传凭证接口
      // 注意: 这里是测试 demo 所以直接调用了获取 UploadAuth 的测试接口, 用户在使用时需要判断 uploadInfo.videoId 存在与否从而调用 openApi
      // 如果 uploadInfo.videoId 存在, 调用 刷新视频上传凭证接口(https://help.aliyun.com/document_detail/55408.html)
      // 如果 uploadInfo.videoId 不存在,调用 获取视频上传地址和凭证接口(https://help.aliyun.com/document_detail/55407.html)
      if (!uploadInfo.videoId) {
        console.log(uploadInfo.file, 'uploadInfoooo')
        let createUrl = '/yyx/getUploadAuth'
        let data = {
          filename: uploadInfo.file.name,
          size: uploadInfo.file.size,
          type: uploadInfo.file.type,
          CateId: 1000579808
        }
        axios.post(createUrl, data).then(({ data }) => {
          console.log(data)
          console.log(uploadInfo, 'cccc')
          let uploadAuth = data.data.uploadAuth
          //console.log(uploadAuth, 'uploadAuth')
          let uploadAddress = data.data.uploadAddress
          //console.log(uploadAddress, 'uploadAddress')
          let videoId = data.data.videoId
          //console.log(videoId, 'videoId')
          uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAuth,
            uploadAddress,
            videoId
          )
        })

        vod.statusText = '文件开始上传...'
        console.log(
          'onUploadStarted:' +
            uploadInfo.file.name +
            ', endpoint:' +
            uploadInfo.endpoint +
            ', bucket:' +
            uploadInfo.bucket +
            ', object:' +
            uploadInfo.object
        )
      } else {
        console.log(uploadInfo.videoId, '*****')
        // 如果videoId有值，根据videoId刷新上传凭证
        // https://help.aliyun.com/document_detail/55408.html?spm=a2c4g.11186623.6.630.BoYYcY
        let refreshUrl = '/yyx/refreshUploadAuth'

        const data = {
          uploadVideoId: uploadInfo.videoId
        }

        axios.post(refreshUrl, data).then(({ data }) => {
          console.log(data, 'data')
          let uploadAuth = data.data.uploadAuth
          console.log(uploadAuth)
          let uploadAddress = data.data.uploadAddress

          let videoId = data.data.videoId
          uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAuth,
            uploadAddress,
            videoId
          )
        })
      }
    },
    // 文件上传成功
    onUploadSucceed: function (uploadInfo: any) {
      console.log(uploadInfo, 'chenggong')
      console.log(
        'onUploadSucceed: ' +
          uploadInfo.file.name +
          ', endpoint:' +
          uploadInfo.endpoint +
          ', bucket:' +
          uploadInfo.bucket +
          ', object:' +
          uploadInfo.object
      )
      vod.statusText = '文件上传成功!'
    },
    // 文件上传失败
    onUploadFailed: function (uploadInfo: any, code: number, message: string) {
      console.log(
        'onUploadFailed: file:' +
          uploadInfo.file.name +
          ',code:' +
          code +
          ', message:' +
          message
      )
      vod.statusText = '文件上传失败!'
    },
    // 取消文件上传
    onUploadCanceled: function (
      uploadInfo: any,
      code: number,
      message: string
    ) {
      console.log(
        'Canceled file: ' +
          uploadInfo.file.name +
          ', code: ' +
          code +
          ', message:' +
          message
      )
      vod.statusText = '文件已暂停上传'
    },
    // 文件上传进度，单位：字节, 可以在这个函数中拿到上传进度并显示在页面上
    onUploadProgress: function (
      uploadInfo: any,
      totalSize: number,
      progress: number
    ) {
      console.log(
        'onUploadProgress:file:' +
          uploadInfo.file.name +
          ', fileSize:' +
          totalSize +
          ', percent:' +
          Math.ceil(progress * 100) +
          '%'
      )
      let progressPercent = Math.ceil(progress * 100)
      vod.authProgress = progressPercent
      vod.statusText = '文件上传中...'
    }
  })
  return uploader
}

const fileChange = (e: any) => {
  console.log(e.target.files[0])
  vod.file = e.target.files[0]
  if (!vod.file) {
    alert('请先选择需要上传的文件!')
    return
  }

  // console.log(vod.file)
  let title = vod.file.name
  //console.log(title)
  let userData = '{"Vod":{}}'
  if (vod.uploader) {
    vod.uploader.stopUpload()
    vod.authProgress = 0
    vod.statusText = ''
  }
  vod.uploader = createUploader()
  console.log(vod.uploader, 'vod.uploader')
  vod.uploader.addFile(vod.file, null, null, null, userData)
}

const authUpload = () => {
  // 然后调用 startUpload 方法, 开始上传
  if (vod.uploader !== null) {
    vod.uploader.startUpload()
    vod.uploadDisabled = true
    vod.pauseDisabled = false
  }
}
</script>

<style scoped></style>
